//
//  CXJsonHelp.swift
//  CXSwiftDemo
//
//  Created by 潮汐 on 2023/11/29.
//
import Foundation

//读取本地json文件，如：CXListData.json
func getJsonDictionaryFileWithJsonName(jsonName jsonStr: String) -> [String: Any] {
    /**
     本地JSON文件
     注意： json文件必须是如下纯的内容，不能包含一些其他头部信息等。Json文件必须是[ ]包裹最外层
     [
         {
             "code": "00",
             "name": "潮汐",
             "age": 100,
             "phones": [
                 {
                     "name": "公司",
                     "number": "123456"
                 },
                 {
                     "name": "家庭",
                     "number": "001"
                 }
             ]
         }
     ]

     代码文档1：https://blog.51cto.com/u_16213413/7807175
     代码文档2：https://blog.51cto.com/u_16213413/7807175
     
     */
    
    //声明一个字典
    var jsonDict = [String: Any]()
    
    //获取json文件的路径：CXListData，不带.json后缀
    guard let path = Bundle.main.path(forResource: jsonStr, ofType: "json") else {
        fatalError("Unable to find JSON file")
    }
    //读取json文件
    guard let data = FileManager.default.contents(atPath: path) else {
        fatalError("Unable to read JSON file")
    }
    do {
        //解析json文件
        guard let jsonArray = try JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]] else {
            fatalError("Invalid JSON format")
        }
        //取出数组第一个数据
        jsonDict = jsonArray.first ?? [:]
        
    } catch {
        fatalError("Failed to parse JSON data: \(error)")
    }
    return jsonDict
}


/**
 //Swift 字典数组转Json字符串 换行符处理
 //方法一：
 class func jsonArray(res: [Any]) -> String {
        if (!JSONSerialization.isValidJSONObject(res)) {
            print("无法解析出JSONString")
            return " "
        }
        if let data = try? JSONSerialization.data(withJSONObject: res, options: [.fragmentsAllowed,.prettyPrinted]), let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue) as String? {
            return JSONString
        }
        return " "
    }
 
 //方法二：
 class func getJSONStringFromArray(array: [Any]) -> String {
     if (!JSONSerialization.isValidJSONObject(array)) {
         print("无法解析出JSONString")
         return " "
     }
     if let data = try? JSONSerialization.data(withJSONObject: array, options: []), let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue) as String? {
         return JSONString
     }
     return " "
 }
 
 
 */
